package blog.service.impl;

import blog.pojo.Role;
import blog.pojo.User;
import blog.service.RoleService;
import blog.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //MD5加密方式
        String password = "";
        //权限组
        List<GrantedAuthority> authorities = new ArrayList<>();
        //获取密码
        User user = userService.selectByName(username);
        if(user == null){
            return null;
        }
        password += user.getPassword();

        Role role = roleService.selectById(user.getRoleId());
        authorities.add(new SimpleGrantedAuthority(role.getName()));

        return new org.springframework.security.core.userdetails.User(username, password, authorities);
    }
}
